package com.awaken.content.service.dubbo.impl;

import com.awaken.content.models.dto.CartDTO;
import com.awaken.content.models.entity.Cart;
import com.awaken.content.models.entity.Product;
import com.awaken.content.models.request.CartRequest;
import com.awaken.content.mapper.CartMapper;
import com.awaken.content.mapper.ProductMapper;
import com.awaken.content.service.dubbo.CartDubboService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车Dubbo服务实现类
 *
 * @author awaken-lin
 */
@Slf4j
@Service
public class CartDubboServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartDubboService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public CartDTO addToCart(CartRequest request) {
        log.info("添加商品到购物车: userId={}, productId={}, quantity={}", 
                request.getUserId(), request.getProductId(), request.getQuantity());
        
        // 检查商品是否存在
        Product product = productMapper.selectById(request.getProductId());
        if (product == null) {
            log.warn("商品不存在: {}", request.getProductId());
            return null;
        }
        
        // 检查购物车是否已存在该商品
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", request.getUserId());
        queryWrapper.eq("product_id", request.getProductId());
        Cart existingCart = this.getOne(queryWrapper);
        
        if (existingCart != null) {
            // 更新数量
            existingCart.setQuantity(existingCart.getQuantity() + request.getQuantity());
            existingCart.setUpdateTime(LocalDateTime.now());
            this.updateById(existingCart);
            
            return convertToCartDTO(existingCart, product);
        } else {
            // 新增购物车项
            Cart cart = new Cart();
            cart.setUserId(request.getUserId());
            cart.setProductId(request.getProductId());
            cart.setQuantity(request.getQuantity());
            cart.setSelected(1);
            cart.setCreateTime(LocalDateTime.now());
            
            this.save(cart);
            
            return convertToCartDTO(cart, product);
        }
    }

    @Override
    public boolean removeFromCart(Long userId, Long productId) {
        log.info("从购物车移除商品: userId={}, productId={}", userId, productId);
        
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);
        
        return this.remove(queryWrapper);
    }

    @Override
    public CartDTO updateCartQuantity(Long userId, Long productId, Integer quantity) {
        log.info("更新购物车商品数量: userId={}, productId={}, quantity={}", userId, productId, quantity);
        
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);
        Cart cart = this.getOne(queryWrapper);
        
        if (cart == null) {
            log.warn("购物车项不存在: userId={}, productId={}", userId, productId);
            return null;
        }
        
        cart.setQuantity(quantity);
        cart.setUpdateTime(LocalDateTime.now());
        this.updateById(cart);
        
        Product product = productMapper.selectById(productId);
        return convertToCartDTO(cart, product);
    }

    @Override
    public List<CartDTO> getUserCart(Long userId) {
        log.info("获取用户购物车: userId={}", userId);
        
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Cart> carts = this.list(queryWrapper);
        
        return carts.stream()
                .map(cart -> {
                    Product product = productMapper.selectById(cart.getProductId());
                    return convertToCartDTO(cart, product);
                })
                .collect(Collectors.toList());
    }

    @Override
    public boolean clearUserCart(Long userId) {
        log.info("清空用户购物车: userId={}", userId);
        
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        return this.remove(queryWrapper);
    }

    @Override
    public boolean toggleCartItemSelected(Long userId, Long productId) {
        log.info("切换购物车商品选择状态: userId={}, productId={}", userId, productId);
        
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("product_id", productId);
        Cart cart = this.getOne(queryWrapper);
        
        if (cart == null) {
            log.warn("购物车项不存在: userId={}, productId={}", userId, productId);
            return false;
        }
        
        cart.setSelected(cart.getSelected() == 1 ? 0 : 1);
        cart.setUpdateTime(LocalDateTime.now());
        
        return this.updateById(cart);
    }
    
    /**
     * 转换为CartDTO
     */
    private CartDTO convertToCartDTO(Cart cart, Product product) {
        CartDTO cartDTO = new CartDTO();
        BeanUtils.copyProperties(cart, cartDTO);
        
        if (product != null) {
            cartDTO.setProductName(product.getName());
            cartDTO.setProductImage(product.getImages());
            cartDTO.setProductPrice(product.getPrice());
        }
        
        return cartDTO;
    }
} 